package com.hrabun.goodmorningalarm;

import java.util.Calendar;
import java.util.Date;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;

public class Alarm extends BroadcastReceiver {

	int alarmID;

	public Alarm() {
	}

	@SuppressWarnings("unused")
	@Override
	public void onReceive(Context context, Intent intent) {
		AlarmItem aItem = new AlarmItem();
		aItem = aItem.getAlarmItemById(intent.getAction());
		int curWeekDay = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
		if (aItem.active && aItem.isValidForToday(curWeekDay) 
				&& (intent.getExtras().getInt(Intent.EXTRA_ALARM_COUNT) == 1)
				&& aItem.isValidForTime()) {
			String action = intent.getAction();
			Toast.makeText(context, "Intent id = " + action, Toast.LENGTH_LONG).show();
			Intent wakeUpIntent = new Intent(context, WakeUpActivity.class);
			wakeUpIntent.putExtra("radio", aItem.getRadioAssignedID());
			wakeUpIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	//		wakeUpIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
	//		wakeUpIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			context.startActivity(wakeUpIntent);
			
		}

	}

	public void setAlarm(Context context, String id, Date time) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(time);
		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, Alarm.class);
		intent.setAction(id);
		PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent,0);

		Log.d("MY", cal.getTime().toString());
		am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pIntent);
		
		//am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pIntent);
	}

	public void cancelAlarm(Context context, String id) {
		Intent intent = new Intent(context, Alarm.class);
		intent.setAction(id);
		PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent,
				0);
		AlarmManager alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		alarmMgr.cancel(pIntent);
	}

	public int getAlarmID() {
		return alarmID;
	}

	public void setAlarmID(int alarmID) {
		this.alarmID = alarmID;
	}

}
